import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { StudyRecord } from '../models/StudyRecord';
import { Word } from '../models/Word';
import { AuthRequest } from '../middlewares/auth';

// 获取学习记录列表
export const getStudyRecords = async (req: AuthRequest, res: Response) => {
  try {
    const { page = 1, limit = 10, startDate, endDate } = req.query;
    const studyRecordRepository = getRepository(StudyRecord);
    const queryBuilder = studyRecordRepository.createQueryBuilder('studyRecord')
      .leftJoinAndSelect('studyRecord.word', 'word')
      .where('studyRecord.user.id = :userId', { userId: req.user.id });

    if (startDate && endDate) {
      queryBuilder.andWhere('studyRecord.studyTime BETWEEN :startDate AND :endDate', {
        startDate,
        endDate
      });
    }

    const [records, total] = await queryBuilder
      .skip((Number(page) - 1) * Number(limit))
      .take(Number(limit))
      .orderBy('studyRecord.studyTime', 'DESC')
      .getManyAndCount();

    res.json({
      records,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit))
    });
  } catch (error) {
    res.status(500).json({ message: '获取学习记录失败', error: error.message });
  }
};

// 创建学习记录
export const createStudyRecord = async (req: AuthRequest, res: Response) => {
  try {
    const { wordId, studyType, studyResult, studyDuration } = req.body;
    const studyRecordRepository = getRepository(StudyRecord);
    const wordRepository = getRepository(Word);

    const word = await wordRepository.findOne({ where: { id: wordId } });
    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }

    const newStudyRecord = studyRecordRepository.create({
      user: { id: req.user.id },
      word,
      studyType,
      studyResult,
      studyDuration,
      studyTime: new Date()
    });

    await studyRecordRepository.save(newStudyRecord);
    res.status(201).json(newStudyRecord);
  } catch (error) {
    res.status(500).json({ message: '创建学习记录失败', error: error.message });
  }
};

// 获取学习统计
export const getStudyStats = async (req: AuthRequest, res: Response) => {
  try {
    const { startDate, endDate } = req.query;
    const studyRecordRepository = getRepository(StudyRecord);

    const queryBuilder = studyRecordRepository.createQueryBuilder('studyRecord')
      .where('studyRecord.user.id = :userId', { userId: req.user.id });

    if (startDate && endDate) {
      queryBuilder.andWhere('studyRecord.studyTime BETWEEN :startDate AND :endDate', {
        startDate,
        endDate
      });
    }

    // 获取总学习时长
    const totalDuration = await queryBuilder
      .select('SUM(studyRecord.studyDuration)', 'totalDuration')
      .getRawOne();

    // 获取学习单词数
    const totalWords = await queryBuilder
      .select('COUNT(DISTINCT studyRecord.word.id)', 'totalWords')
      .getRawOne();

    // 获取正确率
    const correctRate = await queryBuilder
      .select('AVG(CASE WHEN studyRecord.studyResult = :correct THEN 1 ELSE 0 END)', 'correctRate')
      .setParameter('correct', 'correct')
      .getRawOne();

    // 获取每日学习时长
    const dailyDuration = await queryBuilder
      .select('DATE(studyRecord.studyTime)', 'date')
      .addSelect('SUM(studyRecord.studyDuration)', 'duration')
      .groupBy('DATE(studyRecord.studyTime)')
      .orderBy('date', 'ASC')
      .getRawMany();

    res.json({
      totalDuration: totalDuration.totalDuration || 0,
      totalWords: totalWords.totalWords || 0,
      correctRate: correctRate.correctRate || 0,
      dailyDuration
    });
  } catch (error) {
    res.status(500).json({ message: '获取学习统计失败', error: error.message });
  }
}; 